//
//  ZShoppingCarViewController.m
//  shopSN
//
//  Created by yisu on 16/6/12.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZShoppingCarViewController.h"
#import "ZPayViewController.h"//支付页面

#import "ZYSLoginViewController.h"//亿速登录

//subView
#import "ZShoppingCarBottomView.h"
#import "ZShoppingCarSectionView.h"
#import "ZShoppingCarCell.h"
@interface ZShoppingCarViewController ()<UITableViewDataSource, UITableViewDelegate, ZShoppingCarCellDelegate, ZShoppingCarBottomViewDelegate>
{
    UIView *topMenuView;   //顶部交互视图
    UIView *menuBtnView;   //按钮视图
   
    BaseTableView *_tableView;//购物商品列表
    UIView *footerView; //
    
    //NSArray *_dataSource;//购物车数据
    NSMutableArray *_selectedArr;//记录选择状态的arr
    NSInteger _totalMoney;
    
    NSMutableArray *_dataArray;//搜索结果存储数组
    NSArray *_currentDataArray;//当前数据
    int _currentPage;//页数
    
    NSString *tempID;//临时存放用户id
}

/** */
@property (nonatomic, strong) ZShoppingCarBottomView *bottomView;

@end

@implementation ZShoppingCarViewController

#pragma mark - ===== 页面设置 =====
- (void)viewWillAppear:(BOOL)animated {
    
//    //判断用户是否有变化
//    if (IsNilString([UdStorage getObjectforKey:Userid])) {
//        [self loginAction];
//    }else{
//        
//        
//        NSLog(@"id:%@",tempID);
//        if (![tempID isEqualToString:[UdStorage getObjectforKey:Userid]]) {
//            [self userDidChange];
//    }

    
    
    //初始化 数据
    _currentPage = 1;

    //取消table footer
    [_tableView headerEndRefreshing];
    _tableView.footerHidden = NO;
    _tableView.tableFooterView.hidden = YES;
    //重新获取数据
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
         [self getPostData];
     });
        self.navigationController.navigationBarHidden = YES;
        //self.tabBarController.tabBar.hidden =YES;
        //[self viewDidLoad];
        
//    }


}
//翻页调用方法
-(void)getPostData{
    //判断当前页
    if (_currentPage == 0) {
        _currentPage = 1;
    }

    NSString *path = @"Cart/displayGoodsCart";
    NSString *pageStr = [NSString stringWithFormat:@"%d",_currentPage];
//    NSDictionary *params =@{@"user_id":[UdStorage getObjectforKey:Userid],
//                            @"page":pageStr,
//                            @"pagesize":@"10"};
    NSDictionary *params = @{@"page":pageStr,@"token":[UdStorage getObjectforKey:Userid]};
    [ZHttpRequestService POSTGoods:path withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            [_dataArray removeAllObjects];
            NSArray *data=jsonDic[@"data"];
            NSLog(@"getcart---%@", data);
          
            //_dataSource = data;
            _currentDataArray = data;
            [_dataArray addObjectsFromArray:data];
            
            [_selectedArr removeAllObjects];
            for (int idx = 0; idx<_dataArray.count; idx++) {
                [_selectedArr addObject:@"0"];
            }
            
            [_tableView reloadData];
            _totalMoney = 0;
            _bottomView.totalNowMoneyLb.text = @"合计：¥0.00";
            
        }else{
            
            footerView.hidden = NO;
            [_tableView reloadData];
            _currentPage--;
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"请求失败" duration:SXLoadingTime];
        _currentPage--;
        //NSLog(@"%@",error);
    } animated:YES withView:nil];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLb.text = @"购物车";
    
    //初始 数据
    _currentPage = 0;
    _dataArray = [NSMutableArray array];
    
    //初始化 中间视图 相关子视图
    [self initSubViews:self.mainMiddleView];
    
    _selectedArr = [@[] mutableCopy];
    
    [self getPostData];

//    tempID = [UdStorage getObjectforKey:Userid];
}

#pragma mark - 中间视图部分 相关子视图
//初始化子视图
- (void)initSubViews:(UIView *)view {
    
    //1 购物商品列表
    _tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, CGRectW(view), CGRectH(view)-90)];
    _tableView.backgroundColor = HEXCOLOR(0xf0f0f0);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate   = self;
    _tableView.dataSource = self;
    [view addSubview:_tableView];
    
    footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectW(view), 30)];
    UILabel *endNoteLb = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectH(footerView)-20, CGRectW(footerView)-20, 20)];
    [footerView addSubview:endNoteLb];
    endNoteLb.font = MFont(14);
    endNoteLb.textAlignment = NSTextAlignmentCenter;
    endNoteLb.text = @"没有更多数据了 ...";
    footerView.hidden = YES;
    _tableView.tableFooterView = footerView;
    
    
    //刷新控件
    //[_tableView addHeaderWithTarget:self action:@selector(refreshGoodsData)];//下拉刷新
    [_tableView addFooterWithTarget:self action:@selector(loadMoreGoodsData)];//上拉加载更多
    
    

    //底部视图
    _bottomView = [[ZShoppingCarBottomView alloc] initWithFrame:CGRectMake(0, CGRectYH(_tableView), CGRectW(view), 40)];
    [view addSubview:_bottomView];
    _bottomView.delegate = self;
    
    //清空购物车按钮
    UIButton *deletAllBtn = [[UIButton alloc] initWithFrame:CGRectMake(__kWidth-70, 20, 60, 40)];
    deletAllBtn.backgroundColor = [UIColor whiteColor];
    [deletAllBtn setTitle:@"清空" forState:0];
    deletAllBtn.titleLabel.font = MFont(14);
    [deletAllBtn setTitleColor:__DefaultColor forState:0];//修改颜色
    [deletAllBtn setImage:MImage(@"close") forState:0];
    [deletAllBtn addTarget:self action:@selector(respondsToDeletAllBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:deletAllBtn];

}
//删除购物车所有商品
-(void)respondsToDeletAllBtn:(UIButton *)sender{
    WK(weakSelf)
    [ZHttpRequestService POSTGoods:@"Cart/clearAllGoods" withParameters:@{@"token":[UdStorage getObjectforKey:Userid]} success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
                                                                          if (succe) {
                                                                              
                                                                              [_dataArray removeAllObjects];
                                                                              [_tableView reloadData];
                                                                          }else{
                                                                              NSString *message = jsonDic[@"message"];
                                                                             
                                                                              [SXLoadingView showAlertHUD:message duration:2];
                                                                          }
                                                                      } failure:^(NSError *error) {
                                                                          
                                                                      } animated:YES withView:nil];
}



#pragma mark - 底部视图代理方法 bottomViewDelegate
- (void)didAllCheckButton:(BOOL)_check {
    if (_check) {
            for (int idx = 0; idx<_selectedArr.count; idx++) {
              _selectedArr[idx] = @"1";
            }
        
            [_tableView reloadData];
        
            __block  CGFloat totleMoney = 0;
        
            [_selectedArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isEqualToString:@"1"]) {
        
//                    totleMoney+= [_dataSource[idx][@"price_new"] floatValue] *[_dataSource[idx][@"goods_num"] integerValue];
                    totleMoney+= [_dataArray[idx][@"price_new"] floatValue] *[_dataArray[idx][@"goods_num"] integerValue];
        
                }
            }];
            
            _bottomView.totalNowMoneyLb.text = [NSString stringWithFormat:@"合计：¥%.2lf",totleMoney];
    }else {
        for (int idx = 0; idx<_selectedArr.count; idx++) {
            _selectedArr[idx] = @"0";
            
        }
        [_tableView reloadData];
        _bottomView.totalNowMoneyLb.text = [NSString stringWithFormat:@"合计：¥0.00"];

    }

}
- (void)didSelectPayButton {
    NSLog(@"跳转至 结算页面");
    NSString *cartIdStr = @"";
    
    for (int idx = 0; idx<_selectedArr.count; idx++) {
        if ([_selectedArr[idx] boolValue]) {
            NSDictionary *dic = _dataArray[idx];
            if ([cartIdStr isEqualToString:@""]) {
                cartIdStr = [NSString stringWithFormat:@"%@",dic[@"cart_id"]];

            }else{
            cartIdStr = [NSString stringWithFormat:@"%@,%@",cartIdStr,dic[@"cart_id"]];
            }
        }
    }
    if ([cartIdStr isEqualToString:@""]) {
        [SXLoadingView showAlertHUD:@"请选择至少一个商品" duration:0.5];
        
        return;
    }
    
    
    NSDictionary *paraDic = @{@"cart_id":cartIdStr,@"token":[UdStorage getObjectforKey:Userid]};
    
    [ZHttpRequestService POSTGoods:@"Order/settlement" withParameters:paraDic success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
                                                                          if (succe) {
                                                                              
                                                                              ZPayViewController *vc = [[ZPayViewController alloc] initWithArray:jsonDic[@"data"]];
                                                                              
                                                                              [self.navigationController pushViewController:vc animated:YES];
                                                                             
                                                                          }else{
                                                                              NSString *message = jsonDic[@"message"];
                                                                              
                                                                              [SXLoadingView showAlertHUD:message duration:2];
                                                                          }
                                                                      } failure:^(NSError *error) {
                                                                          
                                                                      } animated:YES withView:nil];
    
    
    
}

#pragma mark - cell视图代理方法 shoppingCarCellDelegate
//选中单个商品
- (void)shoppingCarCell:(ZShoppingCarCell *)cell didClicSelectButton:(UIButton *)sender{
    
    _selectedArr[cell.tag] =  [_selectedArr[cell.tag] isEqualToString:@"0"]?@"1":@"0";
    [_tableView reloadData];
    
  __block  CGFloat totleMoney = 0;
    
    [_selectedArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:@"1"]) {
            
            totleMoney+= [_dataArray[idx][@"price_new"] floatValue] *[_dataArray[idx][@"goods_num"] integerValue];

        }
    }];
    
    _bottomView.totalNowMoneyLb.text = [NSString stringWithFormat:@"合计：¥%.2lf",totleMoney];
    
}

//删除单个商品
- (void)shoppingCarCellDidSelectDeleteGoods:(ZShoppingCarCell *)cell {

    WK(weakSelf)

    [ZHttpRequestService POSTGoods:@"Cart/delCartByIds" withParameters:@{@"id":cell.cartID
                                                                      ,@"token":[UdStorage getObjectforKey:Userid]} success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
                                                                          if (succe) {
                                                                              //初始化 数据
                                                                              _currentPage = 1;
                                                                              [_dataArray removeAllObjects];

                                                                              [weakSelf getPostData];
                                                                              
                                                                          }else{
                                                                              NSString *message = jsonDic[@"message"];
                                                                              
                                                                              [SXLoadingView showAlertHUD:message duration:2];
                                                                          }
                                                                      } failure:^(NSError *error) {
                                                                          
                                                                      } animated:YES withView:nil];
    
}


//添加减少商品
-(void)shoppingCarCell:(ZShoppingCarCell *)cell ChangeGoodsCount:(NSInteger)count{
    
    WK(weakSelf)
    
     [ZHttpRequestService POSTGoods:@"Cart/editGoodsNum" withParameters:@{@"cart_id":cell.cartID,@"token":[UdStorage getObjectforKey:Userid],@"goods_num":[NSString stringWithFormat:@"%ld",count]} success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
                                                                          if (succe) {
                                                                              //初始化 数据
                                                                              _currentPage = 1;
                                                                              [_dataArray removeAllObjects];
                                                                              [weakSelf getPostData];
                                                                          }else{
                                                                              NSString *message = jsonDic[@"message"];
                                                                              //[SXLoadingView showAlertHUD:@"注册失败" duration:SXLoadingTime];
                                                                              [SXLoadingView showAlertHUD:message duration:2];
                                                                          }
                                                                      } failure:^(NSError *error) {
                                                                          
                                                                      } animated:YES withView:nil];
                                                                         
    
                                                                          
}


#pragma mark - ===== tableView DataSource and Delegate =====
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!_dataArray||_dataArray.count==0) {
        return 0;
    }
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZShoppingCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShoppingCarCell"];
    if (!cell) {
        cell = [[ZShoppingCarCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ShoppingCarCell"];
        cell.delegate = self;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSDictionary *dic = _dataArray[indexPath.row];
    cell.goodID = dic[@"id"];
    cell.cartID = dic[@"cart_id"];
    cell.cellReturnPoint.text = [NSString stringWithFormat:@"送：%@积分",dic[@"fanli_jifen"]];
    cell.sg_imageView.image = MImage(@"");
    [cell.sg_imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",GoodsImageUrl,dic[@"pic_url"]]]];
    cell.sg_descLb.text = dic[@"title"];
    cell.sg_nowPriceLb.text = [NSString stringWithFormat:@"¥%@",dic[@"price_new"]];
    cell.sg_countLb.text = dic[@"goods_num"];
    
    NSString *goooss = dic[@"shoper_name"];
    if ([goooss isKindOfClass:[NSNull class]]) {
        
        
    }
    
    
    NSString *taocanName = [NSString stringWithFormat:@"%@",dic[@"taocan_name"]];
    
    if (taocanName) {
        cell.cellIsSet.text = [NSString stringWithFormat:@"套餐：%@",taocanName];
    }
    NSString *jifen = [NSString stringWithFormat:@"%@",dic[@"fanli_jifen"]];
    if (!jifen) {
        cell.cellReturnPoint.text = [NSString stringWithFormat:@"送：%@积分",jifen];
    }
    if (dic[@"goods_num"]&&dic[@"price_new"]) {
        cell.sg_settleGoodsCountLb.text = [NSString stringWithFormat:@"小计：共%@件",dic[@"goods_num"]];
        
        CGFloat sumPrice =[dic[@"price_new"] floatValue] * [dic[@"goods_num"] integerValue];
        cell.sg_settleNowPriceLb.text = [NSString stringWithFormat:@"¥%.2lf",sumPrice];
    }
    
    cell.tag = indexPath.row;
    cell.shoppingCarCheckButton.selected = [_selectedArr[indexPath.row] boolValue];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 160;
}

#pragma mark - ===== 刷新控件设置内容 =====
#pragma mark - 上拉加载更多
- (void)collectionViewFootLoadAction {
    
    [self loadMoreGoodsData];
}


//加载更多商品
- (void)loadMoreGoodsData {
    
    NSLog(@"商品搜索页面 加载更多");
    [_tableView footerEndRefreshing];
    if (_currentDataArray.count == 10) {
        _currentPage++;
        [self getPostData];
    }else{
        _tableView.footerHidden = YES;
        _tableView.tableFooterView.hidden = NO;
    }
    
}


#pragma mark - 下拉刷新数据
//- (void)refreshGoodsData {
//    NSLog(@"商品搜索页面 下拉刷新");
//    [_tableView headerEndRefreshing];
//    _tableView.footerHidden = NO;
//    _tableView.tableFooterView.hidden = YES;
//    
//    //初始化 数据
//    _currentPage = 1;
//    [_dataArray removeAllObjects];
//    [self getPostData];
//}



#pragma mark - ===== 用户账号切换 刷新页面=====


- (void)userDidChange {
    NSLog(@"id:%@==name:%@===phone:%@", [UdStorage getObjectforKey:Userid], [UdStorage getObjectforKey:UserType], [UdStorage getObjectforKey:UserPhone]);
    tempID = [UdStorage getObjectforKey:Userid];
    
    //初始化 数据
    _currentPage = 1;
    [_dataArray removeAllObjects];
    [self getPostData];
    

}

#pragma mark - ===== 登录 =====

-(void)loginAction{
    if (!IsNilString([UdStorage getObjectforKey:Userid])) {
        [SXLoadingView showAlertHUD:@"您已经登录" duration:1.5];
    }
//    ZLoginViewController *vc = [[ZLoginViewController alloc] init];
    ZYSLoginViewController *vc = [[ZYSLoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}



@end
